<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>跨域问题</title>
  </head>
  <body>
    <button onclick="getStudents()">获取学生信息</button>
    <br /><br />
    <button onclick="addStudent()">复杂请求</button>
    <pre></pre>

    <script>
      // 简单请求
      function getStudents() {
        fetch("http://localhost:8080/api/students")
          .then((res) => res.json())
          .then((val) => {
            console.log("获取到的数据", val);
          });
      }

      // 复杂请求
      function addStudent() {
        const data = { id: 99, name: "xiaoyu", age: 18 };
        fetch("http://localhost:8080/api/addstudent", {
          method: "post",
          headers: {
            //   "Content-Type": "text/plain",
            "Content-Type": "application/json",
            // xiaoyu: "放荡不羁",
          },
          body: JSON.stringify(data),
        })
          .then((res) => res.json())
          .then((val) => {
            console.log(val);
          });
      }
    </script>

    <button onclick="getStudents()">获取学生@@@@数据</button>

    <script>
      function test(data) {
        console.log(data);
      }
      function getStudents() {
        const script = document.createElement("script");
        script.onload = () => {
          script.remove();
        };
        script.src = "http://localhost:8080/teachers?callback=test";
        document.body.append(script);
      }
    </script>
  </body>
</html>
